#pragma once
#include <iostream>
#include <pthread.h>
#include <string>
#include "Log.hpp"
#include <functional>

namespace ThreadModule
{
    using namespace LogModule;
    static int number = 1;
    
    class Thread
    {
        using _fun_c = std::function<void()>; 
    
    void EnableDetach()
    {
        _isdetach = true;
    }

    void EnableRunning()
    {
        _isrunning = true;
    }

    static void* Route(void* args)
    {
        Thread* self = static_cast<Thread*>(args);
        self->EnableRunning();
        if(self->_isdetach)
            self->Detach();
        pthread_setname_np(self->_tid, self->_name.c_str());
        
        self->_fun();
        return nullptr;
    }
    
    public:
        Thread(_fun_c fun)
            :_tid(0),
            _isdetach(false),
            _isrunning(false),
            res(nullptr),
            _fun(fun)
        {
            _name = "thread- " + std::to_string(number++);
        }

        void Detach()
        {
            if(_isdetach)
                return;
            if(_isrunning)
                pthread_detach(_tid);
            EnableDetach();         
        }

        bool Start()
        {
            if(_isrunning)
                return false;
            int n = pthread_create(&_tid,nullptr,Route,this);
            if(n != 0)
                return false;
            else
                return true;
        }

        bool Stop()
        {
            if(_isrunning)
            {
                int n = pthread_cancel(_tid);
                if(n != 0)
                    return false;
                else
                    return true;
            }
            return false;
        }

        void Join()
        {
            if(_isdetach)
                return;
            int n = pthread_join(_tid,&res);
            if(n == 0)
                LOG(LogLevel::INFO) << "join线程成功";
        }
        
        pthread_t Id()
        {
            return _tid;
        }

        ~Thread(){}

    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void* res;
        _fun_c _fun;
    };
}